package com.ggb.smartstudy.controller.admin;

import com.ggb.smartstudy.entity.Result;
import com.ggb.smartstudy.entity.User;
import com.ggb.smartstudy.service.UserService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author gefangjie
 */
@RestController
@RequestMapping("/admin/user")
@Validated
public class UserManageController {

    private final UserService userService;

    public UserManageController(UserService userService) {
        this.userService = userService;
    }

    // 获取所有用户信息
    @GetMapping("/getAll")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    // 通过用户ID获取用户信息
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 更新用户信息
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Integer id, @Valid @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
        return ResponseEntity.ok(user);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        int i = userService.deleteUser(id);
        if (i == 0) {
            return Result.error("删除失败！未找到用户！");
        } else {
            return Result.success("删除成功！");
        }
    }

}
